package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

type UserInfo struct {
	Name string
}

var wg sync.WaitGroup

func main() {
	testCancle()
	/*
		//c := context.Context()
		ctx := context.Background()
		ctx = context.WithValue(ctx, "name", UserInfo{"fengfeng"})
		GetUser(ctx)
	*/
}

func testCancle() {
	t1 := time.Now()
	ctx, cancel := context.WithCancel(context.Background())
	wg.Add(1)
	go func() {
		ip, err := GetIp(ctx)
		fmt.Println(ip, err)

	}()
	go func() {
		time.Sleep(2 * time.Second)
		//取消协程
		cancel()
	}()

	wg.Wait()
	fmt.Println("执行结束")
	fmt.Println("执行完成时间：", time.Since(t1))
}

func GetUser(ctx context.Context) {
	fmt.Println(ctx.Value("name").(UserInfo))
}

func GetIp(ctx context.Context) (ip string, err error) {
	go func() {
		select {
		case <-ctx.Done():
			fmt.Println("协程取消", ctx.Err())
			err = ctx.Err()
			wg.Done()
			return
		}
	}()
	time.Sleep(4 * time.Second)
	ip = "192.168.100.200"
	return
}
